package com.olive.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.olive.constants.UserConstants;
import com.olive.dto.CaptchaImageVO;

import lombok.extern.slf4j.Slf4j;

@RestController
@Slf4j
public class CaptchaController {
	@Autowired
	private DefaultKaptcha defaultKaptcha;

	@RequestMapping("/kaptcha")
	public void getCaptcha(HttpSession session, HttpServletResponse response) {
		String kaptchaText = defaultKaptcha.createText();
		session.setAttribute(UserConstants.CAPTCHA_SESSION_KEY,
				new CaptchaImageVO(kaptchaText, 2 * 60));
		try (ServletOutputStream outputStream = response.getOutputStream()) {
			BufferedImage image = defaultKaptcha.createImage(kaptchaText);
			ImageIO.write(image, "jpg", outputStream);
			outputStream.flush();
		} catch (IOException e) {
			log.warn(e.getMessage(), e);
			throw new RuntimeException( e.getMessage());
		}
	}
}
